import socket
import os

# 1. 创建socket连接
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 2. 绑定ip端口和创建队列
ip_port = ("127.0.0.1", 8080)
server_socket.bind(ip_port)
server_socket.listen(128)

# 3. 接收客户端的请求
client_socket, client_addr = server_socket.accept()
file_name = client_socket.recv(1024).decode("utf-8")
print("接收到了来自 {} 地址, {} 端口的数据,内容是 {}".format(client_addr[0], client_addr[1], file_name))

# 4. 判断是否文件
if os.path.isfile(file_name):  # 如果是一个文件
    print("读取文件,返回客户端")
    with open(file_name, 'rb') as file:
        content = file.read()
        # 返回客户端数据
        client_socket.send(content)
else:
    print("文件不存在")
